using Avalonia.Controls;
using System;
using System.Diagnostics;
using System.Reactive.Disposables; // For CompositeDisposable
using System.Reactive.Linq; // For Observable methods
using Avalonia.Interactivity; // For RoutedEventArgs
using Avalonia.Threading; // For Dispatcher
using Avalonia.ReactiveUI; // Add this using for AvaloniaObjectExtensions and AvaloniaScheduler
using ReactiveUI; // Add this for WhenAnyValue
using DesktopApp.ViewModels; // Add this for viewmodels

namespace DesktopApp.Views.Controls
{
    public partial class LogPreviewControl : UserControl
    {
        private CompositeDisposable? _disposables;
        private TextBox? _textBox;
        private Button? _button;
        private LogPanelViewModel? _logPanelVm; // Hold reference to LogPanelVM

        public LogPreviewControl()
        {
            InitializeComponent();

            // Get LogPanelVm from DataContext when it changes using WhenAnyValue
            this.WhenAnyValue(x => x.DataContext)
                .Subscribe(dataContext =>
                {
                    if (dataContext is MainWindowViewModel shellVm)
                    {
                        _logPanelVm = shellVm.LogPanelVm;
                        Debug.WriteLine("[LogPreviewControl] LogPanelVm obtained from DataContext.");
                    }
                    else
                    {
                        _logPanelVm = null;
                        Debug.WriteLine("[LogPreviewControl] DataContext is not MainWindowViewModel or null.");
                    }
                });

            // Temporary diagnostic: Find the button and attach a Click handler
            var tempButton = this.FindControl<Button>("CreateRuleFromSelectionButton");
            if (tempButton != null)
            {
                tempButton.Click += CreateRuleButton_Click_Diagnostic;
                Debug.WriteLine("[LogPreviewControl] Diagnostic Click handler attached to CreateRuleFromSelectionButton.");
            }
            else
            {
                Debug.WriteLine("[LogPreviewControl] Error: Could not find CreateRuleFromSelectionButton to attach diagnostic handler.");
            }
        }

        // Temporary diagnostic method
        private void CreateRuleButton_Click_Diagnostic(object? sender, RoutedEventArgs e)
        {
            Debug.WriteLine("[LogPreviewControl] CreateRuleFromSelectionButton CLICKED (Diagnostic Handler).");
            // We don't set e.Handled = true here, allowing the event to bubble up 
            // and hopefully trigger the command binding.
        }

        protected override void OnAttachedToVisualTree(Avalonia.VisualTreeAttachmentEventArgs e)
        {
            base.OnAttachedToVisualTree(e);
            Debug.WriteLine("[LogPreviewControl] Attached to visual tree.");

            _disposables = new CompositeDisposable();
            _textBox = this.FindControl<TextBox>("OriginalLogTextBox");
            _button = this.FindControl<Button>("CreateRuleFromSelectionButton");

            if (_textBox != null && _button != null)
            {
                 Debug.WriteLine("[LogPreviewControl] Controls found. Setting up selection observation.");

                var selectionStartChanges = _textBox.WhenAnyValue(x => x.SelectionStart);
                var selectionEndChanges = _textBox.WhenAnyValue(x => x.SelectionEnd);

                var selectionChanges = Observable.CombineLatest(
                    selectionStartChanges,
                    selectionEndChanges,
                    (start, end) => _textBox.SelectedText
                ).DistinctUntilChanged();

                selectionChanges
                    .Throttle(TimeSpan.FromMilliseconds(150))
                    .ObserveOn(AvaloniaScheduler.Instance)
                    .Subscribe(selectedText =>
                    {
                        bool hasSelection = !string.IsNullOrEmpty(selectedText);
                        
                        // Update LogPanelVm property
                        if (_logPanelVm != null)
                        {
                            _logPanelVm.SelectedOriginalLogText = hasSelection ? selectedText : null;
                        }
                        
                        Debug.WriteLine($"[LogPreviewControl] Throttled selection update. HasSelection: {hasSelection}, Button IsEnabled: {_button?.IsEnabled}, Stored in LogPanelVM: '{_logPanelVm?.SelectedOriginalLogText ?? "(VM null)"}'");
                    })
                    .DisposeWith(_disposables);

                Dispatcher.UIThread.Post(() =>
                {
                     if(_textBox != null && _button != null)
                     {
                        bool initialHasSelection = !string.IsNullOrEmpty(_textBox.SelectedText);
                        
                        // Set initial value in LogPanelVm
                        if (_logPanelVm != null)
                        {
                            _logPanelVm.SelectedOriginalLogText = initialHasSelection ? _textBox.SelectedText : null;
                        }
                        Debug.WriteLine($"[LogPreviewControl] Initial button state set. IsEnabled: {_button?.IsEnabled}, Stored in LogPanelVM: '{_logPanelVm?.SelectedOriginalLogText ?? "(VM null)"}'");
                     }
                }, DispatcherPriority.Loaded);
            }
            else
            {
                 if (_textBox == null) Debug.WriteLine("[LogPreviewControl] Error: Could not find OriginalLogTextBox.");
                 if (_button == null) Debug.WriteLine("[LogPreviewControl] Error: Could not find CreateRuleFromSelectionButton.");
            }
        }

        protected override void OnDetachedFromVisualTree(Avalonia.VisualTreeAttachmentEventArgs e)
        {
            base.OnDetachedFromVisualTree(e);
            Debug.WriteLine("[LogPreviewControl] Detached from visual tree. Disposing subscriptions.");
            _disposables?.Dispose(); // Dispose subscriptions
            
            // Temporary diagnostic: Detach the Click handler
            var tempButton = this.FindControl<Button>("CreateRuleFromSelectionButton");
            if (tempButton != null)
            {
                tempButton.Click -= CreateRuleButton_Click_Diagnostic;
                Debug.WriteLine("[LogPreviewControl] Diagnostic Click handler detached.");
            }

            _disposables = null;
            _textBox = null;
            _button = null;
        }

        // --- Undo/Redo Button Click Handlers ---

        private void UndoButton_Click(object? sender, RoutedEventArgs e)
        {
            var textBox = this.FindControl<TextBox>("OriginalLogTextBox");
            if (textBox?.CanUndo ?? false)
            {
                textBox.Undo();
                 Debug.WriteLine("[LogPreviewControl] Undo executed.");
            }
        }

        private void RedoButton_Click(object? sender, RoutedEventArgs e)
        {
            var textBox = this.FindControl<TextBox>("OriginalLogTextBox");
            if (textBox?.CanRedo ?? false)
            {
                textBox.Redo();
                 Debug.WriteLine("[LogPreviewControl] Redo executed.");
            }
        }
    }
} 